package com.qc31.monitorlib.ui.line

import android.view.WindowManager
import androidx.activity.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import autodispose2.autoDispose
import com.qc31.baselib.custom.timer.CustomDatePicker
import com.qc31.baselib.custom.timer.DateFormatUtils
import com.qc31.baselib.utils.ActivityResultUtil.launchAct
import com.qc31.baselib.utils.ActivityResultUtil.registerResultOk
import com.qc31.baselib.utils.ToolbarHelper
import com.qc31.baselib.utils.isFastClick
import com.qc31.baselib.utils.startActivityTo
import com.qc31.comlib.Keys
import com.qc31.comlib.TimeUtil
import com.qc31.comlib.adapter.ChooseTimeAdapter
import com.qc31.comlib.choose.car.ChooseCarActivity
import com.qc31.monitorlib.R
import com.qc31.monitorlib.base.BaseTimeActivity
import com.qc31.monitorlib.databinding.ActivityHistoryLineBinding

/** @Author Jasper @Time 2020/11/30 @Desc 历史轨迹 */
class HistoryLineActivity :
    BaseTimeActivity<ActivityHistoryLineBinding>(ActivityHistoryLineBinding::inflate) {

    private val mViewModel: HistoryLineViewModel by viewModels()

    override fun initView() {
        super.initView()
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)
        ToolbarHelper.setToolbar(this, R.string.title_monitor_history_line)
        initIntent()
        mRecyclerVB.recyclerWrap.layoutManager = GridLayoutManager(this, 4)
        mRecyclerVB.recyclerWrap.adapter = mAdapter.apply {
            setNewInstance(mViewModel.timeList)
            setOnItemClickListener { _, _, position ->
                index = position
                notifyDataSetChanged()
                mViewModel.chooseTime(position)
            }
        }
        mViewModel.toastObserver().autoDispose(scopeProvider).subscribe(this::toastObserver)

        mViewModel.startObserve().autoDispose(scopeProvider).subscribe {
            mTimeVB.lrvStartTime.setRightText(it)
        }

        mViewModel.endObserve().autoDispose(scopeProvider).subscribe {
            mTimeVB.lrvEndTime.setRightText(it)
        }

        mViewModel.historyLineObserver().autoDispose(scopeProvider).subscribe {
            var speed = binding.editThresholdSpeed.text.toString()
            if (speed.isEmpty()) speed = "0"

            startActivityTo<HistoryLineInfoActivity>(this) {
                putExtra(Keys.INTENT_TITLE, mViewModel.carName)
                putExtra(Keys.INTENT_OTHER, speed)
                putExtra(Keys.INTENT_DATA, mViewModel.params)
            }
        }
    }

    private fun initIntent() {
        val carId = intent.getStringExtra(Keys.INTENT_CAR_ID)
        val carName = intent.getStringExtra(Keys.INTENT_PLATE)
        if (carId == null) return
        mViewModel.carId = carId
        mViewModel.carName = carName ?: ""
        mTimeVB.lrvChooseCar.setRightText(carName ?: "")
        mTimeVB.lrvChooseCar.isEnabled = false
    }

    override fun setListener() {
        mTimeVB.lrvChooseCar.rightClick().autoDispose(scopeProvider).subscribe {
            launcher.launchAct<ChooseCarActivity>(this)
        }
        mTimeVB.lrvStartTime.rightClick().autoDispose(scopeProvider).subscribe {
            mViewModel.isStart = true
            mDatePicker.show(mTimeVB.lrvStartTime.getRightText())
        }
        mTimeVB.lrvEndTime.rightClick().autoDispose(scopeProvider).subscribe {
            mViewModel.isStart = false
            mDatePicker.show(mTimeVB.lrvEndTime.getRightText())
        }

        mSureVB.tvSure.setOnClickListener {
            if (isFastClick()) return@setOnClickListener
            mViewModel.getHistory(
                mTimeVB.lrvStartTime.getRightText(),
                mTimeVB.lrvEndTime.getRightText(),
                binding.cbFilterStop.isChecked,
                binding.editThresholdSpeed.text.toString(),
                binding.editThresholdStop.text.toString(),
                binding.cbFilterInvalid.isChecked,
                binding.cbFilterAppend.isChecked
            )
        }
    }

    private val launcher = registerResultOk { result ->
        result.data?.let {
            val carId = it.getStringExtra(Keys.INTENT_CAR_ID)
            val carName = it.getStringExtra(Keys.INTENT_CAR_NAME)
            mTimeVB.lrvChooseCar.setRightText(carName ?: "")
            mViewModel.carId = carId ?: ""
            mViewModel.carName = carName ?: ""
        }
    }


    private val mAdapter: ChooseTimeAdapter by lazy { ChooseTimeAdapter() }

    private val mDatePicker: CustomDatePicker by lazy {
        CustomDatePicker(
            this,
            callback,
            TimeUtil.normalDate,
            mViewModel.nowTimeFormat(),
            true
        ).apply {
            setCanShowPreciseTime(true)
        }
    }


    private val callback: CustomDatePicker.Callback = object : CustomDatePicker.Callback {
        override fun onTimeSelected(timestamp: Long) {
            mAdapter.index = -1
            mAdapter.notifyDataSetChanged()
            val time: String = DateFormatUtils.long2Str(timestamp, true)
            if (mViewModel.isStart) {
                mTimeVB.lrvStartTime.setRightText(time)
            } else {
                mTimeVB.lrvEndTime.setRightText(time)
            }
            mDatePicker.dismiss()
        }
    }
}